package com.sigmatrix.h5.web.controller.front;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sigmatrix.h5.auth.ILoginUser;
import com.sigmatrix.h5.config.LoginUser;
import com.sigmatrix.h5.config.TableUtils;
import com.sigmatrix.h5.entity.AdminArea;
import com.sigmatrix.h5.entity.v2.CodeInspectionRecord;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.message.bigdata.BigDataInspectionMessage;
import com.sigmatrix.h5.service.AdminAreaService;
import com.sigmatrix.h5.service.common.ServiceHelper;
import com.sigmatrix.h5.service.db.CodeInspectionRecordDBService;
import com.sigmatrix.h5.service.inspect.CodeInspectionRecordResp;
import com.sigmatrix.h5.service.inspect.ICodeInspect;
import com.sigmatrix.h5.service.inspect.InspectResult;
import com.sigmatrix.h5.service.log.BigDataLogger;
import com.sigmatrix.h5.web.BaseController;
import com.sigmatrix.h5.web.args.QueryQrCodeParamV2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;


/**
 * 
 * @author wei.wang
 *
 */

@Api(tags="稽查")
@RestController
@RequestMapping("front/inspect")
public class InspectController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(InspectController.class);
	@Autowired
	private ServiceHelper serviceHelper;
	
	@Autowired
	private AdminAreaService adminAreaService;
	
	@Autowired
	private CodeInspectionRecordDBService codeInspectionRecordDBService;
	

	@ApiOperation(value="稽查",response=InspectResult.class)
	@PostMapping("/process")
	public InspectResult doInspect(@LoginUser ILoginUser user,@RequestBody @ApiParam(name="稽查请求参数",value="稽查请求参数",required=true) QueryQrCodeParamV2 vo){
		InspectResult inspectResult = serviceHelper.selectService(user.getEseCode(),ICodeInspect.class,true).inspect(vo, user.getEseCode(),user);
		
		return inspectResult;
	}
	
	@ApiOperation("显示当前用户稽查记录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "isok", value = "是否稽查结果为正常的记录", required = true, dataType = "Boolean", paramType = "path")
		})
	@GetMapping("/record/show/isok/{isok}")
	public List<CodeInspectionRecordResp> inspectRecordShow(@LoginUser ILoginUser user,@PathVariable boolean isok){
		List<CodeInspectionRecord> result = null;
		if(isok){			
			result = codeInspectionRecordDBService.findOKByUserId(user.getEseCode(),user.getAcctId());
		}else{
			result = codeInspectionRecordDBService.findNGByUserId(user.getEseCode(),user.getAcctId());
		}
		
		List<CodeInspectionRecordResp> resultResp = new ArrayList<>();
		for (CodeInspectionRecord codeInspectionRecord : result) {
			CodeInspectionRecordResp resp = new CodeInspectionRecordResp();
			resultResp.add(resp);
			BeanUtils.copyProperties(codeInspectionRecord, resp);//copy
			AdminArea pro = adminAreaService.findByIdFromCache(resp.getProvinceId());
			if(pro!=null){			
				resp.setProvinceName(pro.getName());
			}
			AdminArea ci = adminAreaService.findByIdFromCache(resp.getCityId());
			if(ci!=null){			
				resp.setCityName(ci.getName());
			}
			AdminArea co = adminAreaService.findByIdFromCache(resp.getCountyId());
			if(co!=null){			
				resp.setCountyName(co.getName());
			}
		}
		return resultResp;
	}
	
	
	@ApiOperation(value="保存稽查记录",response=CodeInspectionRecord.class)
	@PostMapping("/save/record")
	public CodeInspectionRecord saveRecord(@LoginUser ILoginUser user,@RequestBody @ApiParam(name="稽查记录对象",value="稽查记录对象",required=true) CodeInspectionRecord record){
		record.setTablePrefix(TableUtils.tablePrefixBy(user.getEseCode()));
		codeInspectionRecordDBService.insert(record);
		log2BigData(record, user);
		return record;
	}

	/**
	 * 大数据日志记录
	 * 
	 * @param record
	 * @param user
	 */
	private void log2BigData(CodeInspectionRecord record,ILoginUser user){
		try {
			BigDataInspectionMessage message = new BigDataInspectionMessage();
			BeanUtils.copyProperties(record, message);
			message.setTopEseId(user.getBasicModuleEseId());
			BigDataLogger.loggerInfo(message.getLogType(), message);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	
//	//TODO 未使用未测
//	@ApiOperation(value="修改图片url",response=InspectResult.class)
//	@ApiImplicitParams({
//		@ApiImplicitParam(name = "record", value = "稽查记录对象", required = true, dataType = "CodeInspectionRecord") })
//	@PostMapping("/update/picture")
//	public boolean updatePictureForInspect(@LoginUser ILoginUser user,@RequestBody @ApiParam(name="稽查记录对象",value="稽查记录对象",required=true) CodeInspectionRecord record){
//		//TODO 入参check
//		CodeInspectionRecord updateRecord = new CodeInspectionRecord();
//		updateRecord.setTablePrefix(TableUtils.tablePrefixBy(user.getEseCode()));
//		updateRecord.setId(record.getId());
//		updateRecord.setPictureUrl(record.getPictureUrl());
//		boolean isUpdated = codeInspectionRecordDBService.updateById(updateRecord);
//		if(isUpdated){
//			CodeInspectionRecord entity = codeInspectionRecordDBService.selectById(record.getId(), TableUtils.tablePrefixBy(user.getEseCode()));	
//			//TODO 删除 blob中的图片。
//			return isUpdated;
//		}
//		throw new MessageException("更新失败。");
//	}
	
}
